/*****************************************************************************/
/* Include Files */

#include "Keypad.h"

#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <linux/input.h>
#include <dirent.h>
#include <Status.h>
#include "Types.h"
//#include  "minui.h"
/*****************************************************************************/
/* Variable Declarations */

static volatile char Is_Keypad_Initialized = 1;
static int Fd_Event1=-1, Fd_Event2=-1;

/*****************************************************************************/
/* Function Definitions */

TINT32 Keypad_Initialize(void)
{
    if (Is_Keypad_Initialized)
    {
        Fd_Event1 = open("/dev/input/event1", O_RDONLY|O_NONBLOCK);
        if (Fd_Event1 < 0)
        {
            return -1;
        }
        Fd_Event2 = open("/dev/input/event2", O_RDONLY|O_NONBLOCK);
        if (Fd_Event2 < 0)
        {
            return STATUS_INITIALIZE_ERROR;
        }
        Is_Keypad_Initialized = TRUE;
    }
    return STATUS_OK;
}

void Keypad_Cleanup(void)
{
    if (!Is_Keypad_Initialized)
    {
        if (Fd_Event1 > 0)
        {
            close(Fd_Event1);
            Fd_Event1 = -1;
        }
        if (Fd_Event2 > 0)
        {
            close(Fd_Event2);
            Fd_Event2 = -1;
        }
        Is_Keypad_Initialized = FALSE;
    }
}

TUINT32 Keypad_Get_IOKeyStatus(void)
{
    struct input_event key_event1, key_event2;
	int ret, ret1;
    do{
		ret = read(Fd_Event1, &key_event1, sizeof(key_event1));
        if (key_event1.type == EV_KEY && key_event1.value)
		{
			switch (key_event1.code)
			{
				case 0x72: 
					 return IO_KEY_VOLDOWN ; //音量-
					 break ;
				case 0x73: 
				     return IO_KEY_VOLUP ;   //音量+
					 break ;
				case 0X74: 
				     return IO_KEY_POWER ;   //电源按键
					 break ;
				default : 
					 return 0 ;
			}
		}
		ret1 = read(Fd_Event2, &key_event2, sizeof(key_event2));
		 if (key_event2.type == EV_KEY && key_event2.value)
		 {
			switch (key_event2.code)
			{
				case 0xdc: 
					 return IO_KEY_HELP ;break ;  //帮助按键--help
				case 0x9e: 
					 return IO_KEY_BACK ;break ;  //返回按键--back
				case 0xa7: 
					 return IO_KEY_MIC  ;break ;  //麦克风按键
				case 0xd4: 
					 return IO_KEY_CAMERA; break ; //摄像头按键--camera
				case 0xac: 
					 return IO_KEY_HOME ;break ;  //主目录按键--HOME
				case 0x58:
					 return IO_KEY_ROTATE;break ; //摄像头旋转按键--ROTATE
				default:
					 return 0;
			}
		 }
		
    }while ( ret > 0 && ret1 > 0);
	
	return 0;
}

/*****************************************************************************/
/* End of File */
